package com.wanchuang.qhbb.dialog;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;


import com.wanchuang.qhbb.R;
import com.wanchuang.qhbb.adapter.SnCodeAdapter;
import com.wanchuang.qhbb.module.machines.AllowSnListBean;
import com.wanchuang.qhbb.view.MaxHeightRecyclerView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import kale.ui.view.dialog.BaseCustomDialog;
import kale.ui.view.dialog.BaseEasyDialog;
import kale.ui.view.dialog.EasyDialog;

/**
 * Created by AndroidIntexh1 on 2018/9/25.
 */

public class RecycleViewDialog extends BaseCustomDialog {

    public static final String KEY_TYPE = "KEY_TYPE";

    public RecycleViewDialog.OnDialogClickListener dialogListener;


    private MaxHeightRecyclerView recyclerView;
    private SnCodeAdapter mAdapter;
    public AllowSnListBean snData;
    private List<Integer> integers = new ArrayList<>();
    private LinearLayoutManager linearLayoutManager;

    private int index = -1;  // 选中默认值

    /**
     * 继承自{@link EasyDialog.Builder}以扩展builder
     */
    public static class Builder extends BaseEasyDialog.Builder<Builder> {

        private RecycleViewDialog.OnDialogClickListener listener;
        private AllowSnListBean datas;
        private Bundle bundle = new Bundle();

        public Builder(@NonNull Context context) {
            super(context);
        }


        public Builder setType(String data) {
            bundle.putString(KEY_TYPE, data);
            return this;
        }


        public RecycleViewDialog.Builder setOnDialogClickListener(RecycleViewDialog.OnDialogClickListener lis) {
            listener = lis;
            return this;
        }

        public RecycleViewDialog.Builder setData(AllowSnListBean data) {
            datas = data;
            return this;
        }


        @NonNull
        @Override
        protected EasyDialog createDialog() {
            RecycleViewDialog dialog = new RecycleViewDialog();
            dialog.setArguments(bundle); // 增加自己的bundle
            dialog.dialogListener = listener;
            dialog.snData = datas;
            return dialog;
        }
    }


    @Override
    protected int getLayoutResId() {
        return R.layout.dialog_recycle_view;
    }

    @Override
    protected void bindViews(View view) {
        recyclerView = findView(R.id.max_recyclerView);
        TextView btn_cancle = findView(R.id.tv_cancel);
        TextView btn_sure = findView(R.id.tv_sure);
        TextView tv_title = findView(R.id.tv_title);
        tv_title.setText(snData.getShowSnNumber() + "\n" + "(" + snData.getUseSnNumber() + "台可调拨/共" + snData.getTotalSnNumber() + "台)");

        initRecyclerView();
        mAdapter.addAll(snData.getSnList());
        btn_cancle.setOnClickListener(view1 -> dismiss());
        btn_sure.setOnClickListener(view12 -> {
            snData.getSelectedSnList().clear();
            for (int i = 0; i < snData.getSnList().size(); i++) {
                if (snData.getSnList().get(i).isSelect()&&snData.getSnList().get(i).getIs_transfer().equals("0")) {
                    snData.getSelectedSnList().add(snData.getSnList().get(i));
                }
            }
            snData.setSelectSnNumber(String.valueOf(snData.getSelectedSnList().size()));
            dismiss();
        });

    }

    @Override
    protected void setViews() {
        setBackground();
        setLayout();

    }

    /**
     * 强制取消背景，保持有透明
     */
    private void setBackground() {
//        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable()); // 去除dialog的背景，即透明
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(0xffffffff)); // 设置白色背景
//        getDialog().getWindow().setBackgroundDrawableResource(R.drawable.dialog_shop_jion_bg); // 设置背景
    }


    /**
     * 也可通过setLayout来设置：
     * getDialog().getWindow().setLayout(dm.widthPixels, getDialog().getWindow().getAttributes().height);
     */
    private void setLayout() {
        Window window = getDialog().getWindow();
        final WindowManager.LayoutParams lp = window.getAttributes();

        // 强制宽高
//        int padding = getResources().getDimensionPixelOffset(R.dimen.dialog_padding);
        lp.width = getScreenWidth(getActivity());
//        lp.height = getResources().getDimensionPixelOffset(R.dimen.dialog_height);

        lp.gravity = Gravity.BOTTOM; // 设置展示的位置
        window.setAttributes(lp);
    }

    @Override
    protected void modifyAlertDialogBuilder(AlertDialog.Builder builder) {
        super.modifyAlertDialogBuilder(builder);
    }

    public static int getScreenWidth(Activity activity) {
        final DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.widthPixels;
    }


    /**
     * 监听输入框内容
     */
    public interface OnDialogClickListener {
        /**
         * Called when a view has been clicked.
         *
         * @param v The view that was clicked.
         */
        void onClick(View v, int positon);
    }

    private void initRecyclerView() {
        linearLayoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(mAdapter = new SnCodeAdapter(getContext()));
        if (getArguments().getString(KEY_TYPE).equals("only")) {
            mAdapter.setOnItemClickListener(position -> {
                AllowSnListBean.SnMessage snBean = snData.getSnList().get(position);
                snBean.setSelect(!snBean.isSelect());
                if (snBean.isSelect()) {
                    integers.add(position);
                } else {
                    integers.remove(Integer.valueOf(position));
                }
                mAdapter.notifyItemChanged(position);
            });
        } else {
            mAdapter.setOnItemClickListener(position -> {
                if (index == -1) {  //index == -1
                    index = position;
                    AllowSnListBean.SnMessage snBean = snData.getSnList().get(position);
                    snBean.setSelect(!snBean.isSelect());
                    mAdapter.notifyItemChanged(position);
                } else {
                    integers.clear();
                    for (int i = 0; i < snData.getSnList().size(); i++) {
                        snData.getSnList().get(i).setSelect(false);
                    }
                    if (position >= index) {
                        for (int i = index; i <= position; i++) {
                            snData.getSnList().get(i).setSelect(true);
                            integers.add(i);
                        }
                    } else {
                        for (int i = index; i >= position; i--) {
                            snData.getSnList().get(i).setSelect(true);//!snBean.isSelect()
                            integers.add(i);
                        }
                    }
                    mAdapter.notifyDataSetChanged();
                }
            });
        }
    }

    private void BubbleSort() {
        //初始化需要得到的数组
        Integer[] arr = new Integer[integers.size()];
        //使用for循环得到数组
        for (int i = 0; i < integers.size(); i++) {
            arr[i] = integers.get(i);
        }
        for (int i = 0; i < arr.length - 1; i++) {//外层循环控制排序趟数
            for (int j = 0; j < arr.length - 1 - i; j++) {//内层循环控制每一趟排序多少次
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
        integers.clear();
        integers.addAll(Arrays.asList(arr));
    }


}
